<template>
  <div class="knowledge-chat-container">
    <!-- 顶部知识库选择区域 -->
    <!-- <el-card class="knowledge-selector">
      <KnowledgeCheckbox v-model="selectedKnowbaseIds" />
    </el-card> -->

    <!-- 中间对话区域 -->
    <el-card class="chat-container">
      <template #header>
        <div class="chat-header">
          <span>知识库问答对话</span>
          <div class="header-actions">
            <!-- 知识库选择按钮 -->
            <el-button 
              size="small" 
              @click="showKnowledgeDialog = true"
            >
              知识库选择
            </el-button>
            <!-- 清空对话按钮 -->
            <el-button 
            size="small" 
            @click="clearChat" 
            :disabled="messages.length === 0"
          >
            清空对话
          </el-button>
          </div>
        </div>
      </template>

      <div ref="chatWindow" class="chat-window">
        <div v-if="messages.length === 0" class="empty-chat">
          <el-empty description="暂无对话记录" />
        </div>
        
        <div v-else class="messages-list">
          <!-- 用户消息 -->
          <div v-for="(message, index) in messages" :key="index" class="message-item"  :class="{'user-message-item': message.type === 'user'}">
            <div :class="['message-bubble', message.type]">
              <div class="message-avatar">
                <el-avatar :size="32">
                  {{ message.type === 'user' ? '用' : 'AI' }}
                </el-avatar>
              </div>
              <div class="message-content">
                <div v-if="message.type === 'ai'" class="ai-message">
                  <!-- AI消息内容 -->
                  <!-- 使用预先渲染的HTML内容 -->
                  <div v-html="message.renderedContent" class="markdown-content"></div>
                  
                  <!-- 图片展示区域 - 修改为同时显示描述和图片 -->
                  <div v-if="message.images && message.images.length" class="image-gallery">
                    <div v-for="image in message.images" :key="image.index" class="image-item">
                      <div class="image-description">{{ image.description }}</div>
                      <el-image 
                        :src="image.url" 
                        :alt="image.description"
                        :preview-src-list="[image.url]"
                        fit="contain"
                        class="content-image"
                        :style="{ maxWidth: getImageSize(image.url) }"
                      >
                        <template #error>
                          <div class="image-error">
                            <el-icon><Picture /></el-icon>
                            <span>图片加载失败</span>
                          </div>
                        </template>
                      </el-image>
                    </div>
                  </div>
                </div>
                
                <div v-else class="user-message">
                  {{ message.content }}
                </div>
              </div>
            </div>
          </div>
          
          <!-- 流式响应中的消息 -->
          <div v-if="isStreaming" class="message-item">
            <div class="message-bubble ai">
              <div class="message-avatar">
                <el-avatar :size="32">AI</el-avatar>
              </div>
              <div class="message-content">
                <!-- <div v-html="renderMarkdown(streamingContent)" class="markdown-content"></div> -->
                  <!-- 使用计算属性渲染流式内容 -->
                <div v-html="renderedStreamingContent" class="markdown-content"></div>
                <!-- 添加光标 -->
                <!-- <span v-if="isStreaming" class="streaming-cursor">|</span> -->
                <!-- 流式响应中的图片展示 -->
                <div v-if="currentImages.length" class="image-gallery">
                  <div v-for="image in currentImages" :key="image.index" class="image-item">
                    <div class="image-description">{{ image.description }}</div>
                    <el-image 
                      :src="image.url" 
                      :alt="image.description"
                      :preview-src-list="[image.url]"
                      fit="contain"
                      class="content-image"
                      :style="{ maxWidth: getImageSize(image.url) }"
                    >
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                          <span>图片加载失败</span>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部输入区域 -->
      <div class="input-area">
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题，按Enter发送（Shift+Enter换行）"
          :disabled="isStreaming || selectedKnowbaseIds.length === 0"
          @keydown.enter="handleKeydown"
        />
        
        <div class="input-actions">
          <el-tooltip content="请至少选择一个知识库" placement="top">
            <span>
              <el-button 
                type="primary" 
                @click="sendMessage" 
                :disabled="isStreaming || selectedKnowbaseIds.length === 0 || !userInput.trim()"
                :loading="isStreaming"
              >
                发送
              </el-button>
            </span>
          </el-tooltip>
          
          <el-button @click="clearInput">
            清空
          </el-button>
        </div>
      </div>
    </el-card>

    <!--知识库选择弹窗-->
     <el-dialog 
      v-model="showKnowledgeDialog" 
      title="选择知识库" 
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="knowledge-dialog-content">
        <!-- 知识库列表 -->
        <div class="knowledge-list">
          <el-table 
            :data="knowledgeBases" 
            style="width: 100%"
            height="400px"
          >
            <el-table-column width="50">
              <template #default="scope">
                <el-checkbox 
                  v-model="selectedKnowbaseIds" 
                  :label="scope.row.know_base_id" 
                  :value="scope.row.know_base_id"
                />
              </template>
            </el-table-column>
            <el-table-column prop="know_base_name" label="知识库名称" />
            <el-table-column prop="create_date" label="创建日期" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.create_date) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页控件 -->
        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalKnowledgeBases"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showKnowledgeDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmKnowledgeSelection">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick,computed ,watch,onMounted} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
// import KnowledgeCheckbox from '@/components/chat/KnowledgeCheckbox.vue';
import ChatMessage from '@/components/chat/RagMessage.vue';
import { ragQueryStream } from '@/services/rag';
import { renderMarkdown } from '@/utils/markdownRender';
import { getKnowledgeBases } from '@/services/rag';

const selectedKnowbaseIds = ref([]);
const userInput = ref('');
const messages = ref([]);
const isStreaming = ref(false);
const streamingContent = ref('');
const chatWindow = ref(null);

// 新增：知识库相关状态
const showKnowledgeDialog = ref(false);
const knowledgeBases = ref([]);
const totalKnowledgeBases = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 新增：图片预览相关状态
const previewVisible = ref(false);
const previewImageUrl = ref('');
const previewImageList = ref([]);
const previewImageIndex = ref(0);
const currentImages = ref([]); // 存储当前流式响应中的图片

// 新增：流式文本缓冲区
const streamingBuffer = ref('');

// 使用计算属性来处理 Markdown 渲染
const renderedStreamingContent = computed(() => {
  return renderMarkdown(streamingContent.value);
});

// 获取图片显示尺寸
const getImageSize = (url) => {
  // 根据图片URL或类型决定显示尺寸
  if (url.includes('table')) {
    return '100%'; // 表格图片全宽显示
  }
  return '400px'; // 其他图片固定宽度
};

// 为消息添加渲染后的内容
const processedMessages = computed(() => {
  return messages.value.map(message => {
    if (message.type === 'ai') {
      return {
        ...message,
        renderedContent: renderMarkdown(message.content)
      };
    }
    return message;
  });
});

// 新增：格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString();
};

// 新增：处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchKnowledgeBases();
};

// 新增：获取知识库列表
const fetchKnowledgeBases = async () => {
  try {
    const response = await getKnowledgeBases({
      page: currentPage.value,
      page_size: pageSize.value
    });
    
    knowledgeBases.value = response.list || [];
    totalKnowledgeBases.value = response.total_items || 0;
  } catch (error) {
    console.error('获取知识库列表失败:', error);
    ElMessage.error('获取知识库列表失败');
  }
};


// 新增：确认知识库选择
const confirmKnowledgeSelection = () => {
  showKnowledgeDialog.value = false;
  // 这里可以添加额外的确认逻辑
};

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || selectedKnowbaseIds.value.length === 0 || isStreaming.value) {
    return;
  }

  const question = userInput.value.trim();
  
  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: question,
    // renderedContent: question // 用户消息不需要 Markdown 渲染
  });

  // 清空输入框
  userInput.value = '';
  isStreaming.value = true;
  streamingContent.value = '';
  streamingBuffer.value = ''; // 清空缓冲区
  currentImages.value = []

  try {
    // 调用RAG流式接口
    await ragQueryStream(
      {
        knowledge_bases: selectedKnowbaseIds.value,
        question: question
      },
      // 数据接收回调
      (data) => {
       
          console.log(data)
        if (data.text) {
          console.log(data.text)
          // 接收到文本数据
          //将新文本添加到缓冲区
          streamingContent.value += data.text;
          // scrollToBottom();
        } else if (data.images && data.type === 'images_info') {
          // 处理图片数据 - 取消注释并修改
          currentImages.value = data.images;
          // scrollToBottom();
        }  else if (data.error) {
          // 接收到错误信息
          ElMessage.error(`服务器错误: ${data.error}`);
        }
        // 可以处理其他类型的data，如图片、表格等
        
        
      },
      // 流完成回调
      () => {
        // 确保缓冲区内容全部显示
        if (streamingBuffer.value) {
          streamingContent.value += streamingBuffer.value;
          streamingBuffer.value = '';
        }
         // 流完成回调 - 修改：保存图片数据到消息中
        // 流式完成，添加到消息列表
        if (streamingContent.value || currentImages.value.length) {
           const newMessage = {
            type: 'ai',
            content: streamingContent.value,
            images: [...currentImages.value],
            // 预先计算渲染内容
            renderedContent: renderMarkdown(streamingContent.value)
          };
          
          // 添加到消息列表
          messages.value.push(newMessage);
           // 滚动到底部
          scrollToBottom();
          // messages.value.push({
          //   type: 'ai',
          //   content: streamingContent.value,
          //   images: [...currentImages.value] // 保存图片数据
          // });
        }
        resetStreaming();
      },
      // 错误回调
      (error) => {
        console.error('流式请求错误:', error);
        ElMessage.error('请求失败: ' + error.message);
        resetStreaming();
      }
    );

  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送失败，请检查网络连接');
    resetStreaming();
  }
};

// 组件挂载时获取知识库列表
onMounted(() => {
  fetchKnowledgeBases();
});

// 新增：处理图片预览
const handleImagePreview = (imageUrl, imageList) => {
  previewImageUrl.value = imageUrl;
  previewImageList.value = imageList || [imageUrl];
  previewImageIndex.value = previewImageList.value.indexOf(imageUrl);
  previewVisible.value = true;
};

// 处理键盘事件
const handleKeydown = (event) => {
  if (event.shiftKey) {
    // Shift+Enter 换行
    return;
  }
  
  // Enter 发送消息
  event.preventDefault();
  sendMessage();
};

// 清空输入
const clearInput = () => {
  userInput.value = '';
};

// 清空对话
const clearChat = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有对话记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    messages.value = [];
  } catch {
    // 用户取消
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatWindow.value) {
      // 确保滚动到最底部
      chatWindow.value.scrollTop = chatWindow.value.scrollHeight;
      
      // 添加额外检查，确保滚动位置正确
      const checkScroll = () => {
        const scrollDiff = chatWindow.value.scrollHeight - 
                          (chatWindow.value.scrollTop + chatWindow.value.clientHeight);
        
        if (scrollDiff > 10) { // 如果还有10px以上的内容不可见
          chatWindow.value.scrollTop = chatWindow.value.scrollHeight;
          setTimeout(checkScroll, 50); // 再次检查
        }
      };
      
      setTimeout(checkScroll, 100);
    }
  });
};

// 重置流式状态
const resetStreaming = () => {
  isStreaming.value = false;
  streamingContent.value = '';
  currentImages.value = [];
  streamingBuffer.value = '';
};

</script>

<style scoped>

/* 头部操作按钮布局 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 知识库弹窗样式 */
.knowledge-dialog-content {
  display: flex;
  flex-direction: column;
  height: 550px;
}

.knowledge-list {
  flex: 1;
  overflow-y: auto;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
.knowledge-chat-container {
  display: grid;
  padding:0px;
  max-width: 1200px;
  margin: 0 auto;
  grid-template-rows: auto 1fr;
  height: 89vh;
  overflow: hidden;
}

.knowledge-selector {
  margin-bottom: 20px;
  grid-row:1;
}

.chat-container {
  /* height: calc(100vh - 150px); */
  display: flex;
  flex-direction: column;
   grid-row: 2;
   height: 100%;
}



.chat-window {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  margin-bottom: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  height: 60vh;
  /* 添加滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c0c0c0 #f0f0f0;
}

/* 自定义滚动条样式 */
.chat-window::-webkit-scrollbar {
  width: 8px;
}

.chat-window::-webkit-scrollbar-track {
  background: #f0f0f0;
  border-radius: 4px;
}

.chat-window::-webkit-scrollbar-thumb {
  background: #c0c0c0;
  border-radius: 4px;
}

.chat-window::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0;
}

.empty-chat {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 100%; 
}

.message-item {
  display: flex;
}

.message-bubble {
  display: flex;
  gap: 12px;
  max-width: 100%;
}

.message-bubble.user {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  max-width: calc(100% - 44px); /* 头像宽度 + 间隙 */
  overflow: hidden; /* 防止内容溢出 */
}

.ai-message, .user-message {
  background: #f5f7fa;
  padding: 12px 16px;
  border-radius: 8px;
  max-width: 100%;
  word-break: break-word; /* 确保长单词可以换行 */
}

.user-message-item {
  justify-content: flex-end; /* 用户消息靠右显示 */
}

.user-message {
  background: #e1f5fe;
}

.markdown-content {
  line-height: 1.6;
  max-width: 100%;
  overflow: hidden;
}

/* 图片展示样式 */
.image-gallery {
  margin-top: 16px;
}

.image-item {
  margin-bottom: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 12px;
  background: white;
  max-width: 100%;
  overflow: hidden;
}

.image-description {
  font-weight: 500;
  margin-bottom: 8px;
  color: #303133;
  font-size: 14px;
  word-break: break-word;
}

.content-image {
  border-radius: 4px;
  display: block;
  margin: 0 auto;
  max-width: 100%;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #999;
  background: #f5f5f5;
  border-radius: 4px;
}

.input-area {
  border-top: 1px solid #e0e0e0;
  padding-top: 16px;
  height: 120px;
  grid-row: 3;
  margin-top:auto;/*确保输入区域在底部*/ 
  overflow: visible; 
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 12px;
}

/* 流式光标样式 */
.streaming-cursor {
  display: inline-block;
  animation: blink 1s infinite;
  font-weight: bold;
  margin-left: 2px;
}
</style>

<!-- 全局样式 -->
<style>
/* 限制对话框中所有内容的最大宽度 */
.chat-container .message-content {
  max-width: 100%;
}

/* 限制图片最大尺寸 */
.chat-container .content-image {
  max-width: 100% !important;
  height: auto !important;
}

/* 调整Markdown内容中的图片样式 */
.chat-container .markdown-content img {
  max-width: 100% !important;
  height: auto !important;
  display: block;
  margin: 10px auto;
  border-radius: 4px;
}

/* 确保表格不会溢出 */
.chat-container .markdown-content table {
  width: 100% !important;
  max-width: 100% !important;
  border-collapse: collapse;
  overflow-x: auto;
  display: block;
}

.chat-container .markdown-content table th,
.chat-container .markdown-content table td {
  padding: 8px;
  border: 1px solid #ddd;
  word-break: break-word;
}

/* 代码块样式 */
.chat-container .markdown-content pre {
  max-width: 100%;
  overflow-x: auto;
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  margin: 10px 0;
}

.chat-container .markdown-content code {
  background: #f5f7fa;
  padding: 2px 4px;
  border-radius: 4px;
}

/* 标题样式 */
.chat-container .markdown-content h1,
.chat-container .markdown-content h2,
.chat-container .markdown-content h3,
.chat-container .markdown-content h4,
.chat-container .markdown-content h5,
.chat-container .markdown-content h6 {
  margin-top: 16px;
  margin-bottom: 8px;
  max-width: 100%;
}

/* 列表样式 */
.chat-container .markdown-content ul,
.chat-container .markdown-content ol {
  padding-left: 24px;
  max-width: 100%;
}

.chat-container .markdown-content li {
  margin-bottom: 4px;
}

/* 段落样式 */
.chat-container .markdown-content p {
  margin-bottom: 12px;
  max-width: 100%;
  word-break: break-word;
}

/* 引用样式 */
.chat-container .markdown-content blockquote {
  border-left: 4px solid #409eff;
  padding-left: 16px;
  margin: 12px 0;
  color: #555;
  max-width: 100%;
}

/* 打字机效果 */
.markdown-content p,
.markdown-content li,
.markdown-content h1,
.markdown-content h2,
.markdown-content h3 {
  overflow: hidden;
  white-space: pre-wrap; /* 改为pre-wrap以允许换行 */
  /* animation: typing 0.1s steps(40, end); */
}

@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}
</style>